import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class Hello {
    public static void main(String[] args) throws Exception {

        String text = "hello java";

        PublicKey pubKey = PublicKeyReader.get("src/rsa_public_key.der");
        byte[] bytes = RSAUtil.encryptByPublicKey(pubKey, text.getBytes());
        String cipherText = toBase64(bytes);
        System.out.println(cipherText);

        PrivateKey priKey = PrivateKeyReader.get("src/rsa_private_pkcs8.der");
        byte[] cipherBytes = fromBase64(cipherText);
        byte[] result = RSAUtil.decryptByPrivateKey(priKey, cipherBytes);
        System.out.println(new String(result, StandardCharsets.UTF_8));
    }

    public static String toBase64(byte[] bytes) {
        return new BASE64Encoder().encode(bytes);
    }

    public static byte[] fromBase64(String b64String) throws IOException {
        return new BASE64Decoder().decodeBuffer(b64String);
    }
}

class PublicKeyReader {
    public static PublicKey get(String filename) throws Exception {
        byte[] keyBytes = Files.readAllBytes(Paths.get(filename));
        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePublic(spec);
    }
}

class PrivateKeyReader {
    public static PrivateKey get(String filename) throws Exception {
        byte[] keyBytes = Files.readAllBytes(Paths.get(filename));
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePrivate(spec);
    }
}